package com.globallogic.vkulyk.SSHTool;

import java.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jcraft.jsch.Session;

public class ScriptExecutor extends ActionExecutor {
	private String script = "";

	private String host = "";
	private int port = 0;
	private String user = "";
	private String password = "";

	private final Logger logger = LoggerFactory
			.getLogger(ScriptExecutor.class);

	public ScriptExecutor(String hostArg, int portArg,
			String userArg, String passwordArg, String scriptArg) {
		super(hostArg, portArg, userArg, passwordArg);
		host = hostArg;
		port = portArg;
		user = userArg;
		password = passwordArg;
		script = scriptArg;
	}

	public void execute() {
		Session session = openSession();
		executeInExistingSession(session);
		closeSession(session);
	}

	@Override
	public void executeInExistingSession(Session sessionArg) {
		Session session = sessionArg;
		String scriptName = script.replaceAll("^.*/", "").replaceAll("^.*\\\\",
				"");
		logger.info("Executing script '{}'..", scriptName);
		String localTempDir = "temp"; // relative
		String localTempFile = localTempDir + "/" + scriptName;
		String dstTempDir = "/tmp";
		String dstTempFile = dstTempDir + "/" + scriptName;
		
		File tempDir = new File(localTempDir);
		tempDir.mkdir();
		removeReturnsFromScript(script, localTempFile);

		new FilePutter(host, port, user, password, localTempFile,
				dstTempDir).executeInExistingSession(session);
		new CommandExecutor(host, port, user, password, "chmod +x " + dstTempFile)
				.executeInExistingSession(session);
		new CommandExecutor(host, port, user, password, dstTempFile)
				.executeInExistingSession(session);
		new CommandExecutor(host, port, user, password, "rm -f " + dstTempFile)
				.executeInExistingSession(session);
		
		new File(localTempFile).delete();
		tempDir.delete();
	}

	private void removeReturnsFromScript(String inScriptArg, String outScriptArg) {
		String inScript = inScriptArg;
		String outScript = outScriptArg;
		BufferedReader reader = null;
		BufferedWriter writer = null;
		try {
			File inFile = new File(inScript);
			File outFile = new File(outScript);
			reader = new BufferedReader(new FileReader(inFile));
			writer = new BufferedWriter(new FileWriter(outFile));
			String line = null;
			while ((line = reader.readLine()) != null) {
				String modifiedLine = line.replace('\r', ' ');
				writer.write(modifiedLine + "\n");
			}
			writer.flush();
			reader.close();
			writer.close();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			try {
				writer.close();
				reader.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
	}

}
